import React, { useContext, FC } from 'react'
import {
  MenuItemProps,
  getMenuItemClassNames,
  DISPLAY_NAME_MENU_ITEM,
} from './config'
import { MenuContext } from '../../Menu'

export const MenuItem: FC<MenuItemProps> = props => {
  const { index, style, children, disabled } = props
  const context = useContext(MenuContext)
  const MenuItemClasses = getMenuItemClassNames(props, () => {
    return {
      'is-active': context.index === index,
    }
  })

  const handleClick = () => {
    if (context.onSelect && !disabled && typeof index === 'string') {
      context.onSelect(index)
    }
  }

  return (
    <li className={MenuItemClasses} style={style} onClick={handleClick}>
      {children}
    </li>
  )
}
MenuItem.displayName = DISPLAY_NAME_MENU_ITEM

export default MenuItem
